'use strict'

//本机内部视频通讯，当前案例没有通过信令服务器

//获取元素
var localVideo = document.querySelector('video#localVideo')
var remoteVideo = document.querySelector('video#remoteVideo')
var btnStart = document.querySelector('button#start')
var btnCall = document.querySelector('button#call')
var btnHangup = document.querySelector('button#hangup')
var offerSDP = document.querySelector('textarea#offer')
var answerSDP = document.querySelector('textarea#answer')
var pc1,pc2;
var localStream;


offerSDP.innerHTML = 'offer sdp'
answerSDP.value = 'answer sdp'

//获取媒体,并设置到video中
function getMediaStream(stream) {
    localStream = stream
    localVideo.srcObject=stream
}

function handleError(error) {
    console.error('getMediaStream error',error)
}

//绑定点击事件
function start() {
    if (!navigator.mediaDevices||
        !navigator.mediaDevices.getUserMedia) {
        console.error('the getUserMedia is not supported')
    }else{
        var constraints={video:{height:320,with:320},audio:true}
        navigator.mediaDevices.getUserMedia(constraints)
        .then(getMediaStream)
        .catch(handleError)
    }
}


function getRemoteStream(e) {
    //远端流设置
    remoteVideo.srcObject = e.streams[0]
}


function call() {
    
    pc1 = new RTCPeerConnection()
    pc2 = new RTCPeerConnection()

    //候选者监听
    pc1.onicecandidate = (e)=>{
        pc2.addIceCandidate(e.candidate)
    }
    pc2.onicecandidate = (e)=>{
        pc1.addIceCandidate(e.candidate)
    }

    pc2.ontrack = getRemoteStream;


    localStream.getTracks().forEach((track)=>{
        pc1.addTrack(track,localStream) //将本地流添加到pc1中
    })

    //媒体协商
    var offerOptions = {
        offerToReceiveAudio:1,
        offerToReceiveVideo:1
    }

    function getAnswer(desc) {
        answerSDP.value = desc.sdp
        pc2.setLocalDescription(desc)
        pc1.setRemoteDescription(desc)
    }

    function handleAnswerError(error){
        console.error('get answer failed',error);
    }

    function getOffer(desc) {
        //进行媒体协商
        pc1.setLocalDescription(desc)
        //获取sdp
        
        offerSDP.value = desc.sdp
        
        //send desc to signal
        //对端receive desc from signal

        pc2.setRemoteDescription(desc)
        pc2.createAnswer()
        .then(getAnswer)
        .catch(handleAnswerError)
    }

    function handleDescError(error) {
        console.error('create offer failed',error);        
    }

    pc1.createOffer(offerOptions)
    .then(getOffer)
    .catch(handleDescError);

}

function hangup() {
    pc1.close();
    pc2.close();
}


btnStart.onclick = start
btnCall.onclick = call
btnHangup.onclick = hangup